package com.ruoyi.common.utils.python;

import com.ruoyi.common.config.LlmInfoConfig;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Slf4j
@RequiredArgsConstructor
public class PythonCommandUtils {

    private static final String PYTHON_COMMAND_PARAMETER = LlmInfoConfig.getPythonCommandParameter();

    /**
     * 利用python获取Excel文件中的文字内容
     *
     * @param excelFile 本地文件路径
     * @return
     */
    public static String excelToJsonFromPython(String excelFile) {

        try {
            StringBuilder result = new StringBuilder();
            // 从JAR包中读取Python脚本路径
            InputStream inputStream = PythonCommandUtils.class.getClassLoader().getResourceAsStream("py/excel_to_json.py");
            if (inputStream == null) {
                throw new FileNotFoundException("Python script not found in the JAR: py/excel_to_json.py");
            }
            // 明确指定临时文件的存储路径
            File tempDir = new File(System.getProperty("java.io.tmpdir"), "llm-temp");
            tempDir.mkdirs(); // 确保目录存在
            File tempScriptFile = new File(tempDir, "excel_to_json.py");
            String pythonScriptPath = tempScriptFile.getAbsolutePath();
            Files.copy(inputStream, Paths.get(pythonScriptPath), StandardCopyOption.REPLACE_EXISTING);
            tempScriptFile.deleteOnExit();

            log.info("Python file path: {}", pythonScriptPath);

            // 根据需要调整命令和参数
            String[] command = {PYTHON_COMMAND_PARAMETER, pythonScriptPath, excelFile};

            // 使用ProcessBuilder启动进程
            ProcessBuilder pb = new ProcessBuilder(command);

            // 设置环境变量，确保 Python 使用 UTF-8 编码
            pb.environment().put("PYTHONIOENCODING", "utf-8");

            Process process = pb.start();

            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            //System.err.println("读取标准输出：" + reader.readLine());
            String line;
            while ((line = reader.readLine()) != null) {
                //System.err.println(line);
                result.append(line);
            }

            // 读取标准错误输出（可选）
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                log.error("PythonCommandError: " + line);
            }

            // 关闭读取器
            reader.close();
            errorReader.close();

            // 等待进程结束并获取退出值
            int exitCode = process.waitFor();

            // 将 StringBuilder 转换为 UTF-8 编码的字节数组
            byte[] utf8Bytes = result.toString().getBytes(StandardCharsets.UTF_8);

            // 如果需要将字节数组转换回字符串以验证编码
            String jsonStr = new String(utf8Bytes, StandardCharsets.UTF_8);
            //log.info("Excel返回内容: {}", jsonStr);
            return jsonStr;
        } catch (Exception e) {
            log.error("FilePath: " + excelFile + ", ErrorInfo: " + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 利用python获取Excel文件中的文字内容
     *
     * @param excelFile 本地文件路径
     * @return
     */
    public static String excelToMarkdownFromPython(String excelFile, String keywords) {

        try {
            StringBuilder result = new StringBuilder();
            // 从JAR包中读取Python脚本路径
            InputStream inputStream = PythonCommandUtils.class.getClassLoader().getResourceAsStream("py/excel_to_markdown.py");
            if (inputStream == null) {
                throw new FileNotFoundException("Python script not found in the JAR: py/excel_to_markdown.py");
            }
            // 明确指定临时文件的存储路径
            File tempDir = new File(System.getProperty("java.io.tmpdir"), "llm-temp");
            // 确保目录存在
            tempDir.mkdirs();
            File tempScriptFile = new File(tempDir, "excel_to_markdown.py");
            String pythonScriptPath = tempScriptFile.getAbsolutePath();
            Files.copy(inputStream, Paths.get(pythonScriptPath), StandardCopyOption.REPLACE_EXISTING);
            tempScriptFile.deleteOnExit();

            log.info("Python file path: {}", pythonScriptPath);

            // 根据需要调整命令和参数
            String[] command = {PYTHON_COMMAND_PARAMETER, pythonScriptPath, excelFile, keywords};

            // 使用ProcessBuilder启动进程
            ProcessBuilder pb = new ProcessBuilder(command);

            // 设置环境变量，确保 Python 使用 UTF-8 编码
            pb.environment().put("PYTHONIOENCODING", "utf-8");

            Process process = pb.start();

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
                 BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                while ((line = errorReader.readLine()) != null) {
                    log.error("PythonCommandError: " + line);
                }

            } catch (IOException e) {
                log.error("Error reading process output", e);
            }

            /*// 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            //System.err.println("读取标准输出：" + reader.readLine());
            String line;
            while ((line = reader.readLine()) != null) {
                //System.err.println(line);
                result.append(line);
            }

            // 读取标准错误输出（可选）
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                log.error("PythonCommandError: " + line);
            }

            // 关闭读取器
                reader.close();
                errorReader.close();
            */

            // 等待进程结束并获取退出值
            int exitCode = process.waitFor();

            // 将 StringBuilder 转换为 UTF-8 编码的字节数组
            byte[] utf8Bytes = result.toString().getBytes(StandardCharsets.UTF_8);

            // 如果需要将字节数组转换回字符串以验证编码
            String jsonStr = new String(utf8Bytes, StandardCharsets.UTF_8);

            //log.info("Excel返回内容: {}", jsonStr);

            if (StringUtils.isBlank(jsonStr)) {
                jsonStr = excelToJsonFromPython(excelFile);
            }

            return jsonStr;
        } catch (Exception e) {
            log.error("FilePath: " + excelFile + ", ErrorInfo: " + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 利用python获取邮件文件中的文字内容
     *
     * @param emailFile 本地文件路径
     * @return 提取的文本内容
     */
    public static String emailToTextFromPython(String emailFile) {
        try {
            StringBuilder result = new StringBuilder();
            // 从JAR包中读取Python脚本路径
            InputStream inputStream = PythonCommandUtils.class.getClassLoader().getResourceAsStream("py/email_to_text.py");
            if (inputStream == null) {
                throw new FileNotFoundException("Python script not found in the JAR: py/email_to_text.py");
            }
            // 明确指定临时文件的存储路径
            File tempDir = new File(System.getProperty("java.io.tmpdir"), "llm-temp");
            tempDir.mkdirs(); // 确保目录存在
            File tempScriptFile = new File(tempDir, "email_to_text.py");
            String pythonScriptPath = tempScriptFile.getAbsolutePath();
            Files.copy(inputStream, Paths.get(pythonScriptPath), StandardCopyOption.REPLACE_EXISTING);
            tempScriptFile.deleteOnExit();

            log.info("Python file path: {}", pythonScriptPath);

            // 根据需要调整命令和参数
            String[] command = {PYTHON_COMMAND_PARAMETER, pythonScriptPath, emailFile};

            // 使用ProcessBuilder启动进程
            ProcessBuilder pb = new ProcessBuilder(command);

            // 设置环境变量，确保 Python 使用 UTF-8 编码
            pb.environment().put("PYTHONIOENCODING", "utf-8");

            Process process = pb.start();

            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }

            // 读取标准错误输出（可选）
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                log.error("PythonCommandError: " + line);
            }

            // 关闭读取器
            reader.close();
            errorReader.close();

            // 等待进程结束并获取退出值
            int exitCode = process.waitFor();

            // 将 StringBuilder 转换为 UTF-8 编码的字节数组
            byte[] utf8Bytes = result.toString().getBytes(StandardCharsets.UTF_8);

            // 如果需要将字节数组转换回字符串以验证编码
            String textContent = new String(utf8Bytes, StandardCharsets.UTF_8);
            return textContent.trim();
        } catch (Exception e) {
            log.error("FilePath: " + emailFile + ", ErrorInfo: " + e.getMessage());
            e.printStackTrace();
            return "";
        }
    }

}
